import crypto from "crypto"
export type AppTokenObj = {
  userId: number,
  expires: number
  token: string
}

export class AppToken {
  static inst: AppToken = new AppToken()

  static getInstance() {
    return AppToken.inst
  }

  // 缓存 token
  private cache: Map<string, AppTokenObj> = new Map()

  // 创建token
  private createToken(userId: number): AppTokenObj{
    const token = Math.random() + '-' + new Date().getTime

    // 过期时间
    const expires = new Date().getTime() + 1000 * 60 * 60 * 3

    const sha = crypto.createHash("sha1")
    sha.update(token)
    const hash = sha.digest("hex")

    const TOKENOBJ = {
      userId,
      expires,
      token: hash
    }
    
    this.cacheSet(hash, TOKENOBJ)
    
    return TOKENOBJ
  }

  // 设置缓存
  private cacheSet(hash: string, tokenObj: AppTokenObj) {
    this.cache.set(hash, tokenObj)
  }

  // 获取缓存
  private cacheGet(hash: string) {
    return this.cache.get(hash) || null
  }

  // 删除缓存
  public cacheDel(hash: string) {
   return this.cache.delete(hash)
  }

  // 获取token
  public getToken(hash: string): null | AppTokenObj{
    
    const token = this.cacheGet(hash)
    if (!token) {
      return null
    }

    if (token.expires > new Date().getTime()) {
      return token
    }

    this.cacheDel(hash)

    return null
  }

  // 刷新token
  public refreshToken(userId: number, oldHash ?:string): AppTokenObj{
    return this.createToken(userId)
  }
}